import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as os from 'os';
import * as fs from 'fs';
import * as path from 'path';

/**
 * 系统工具类
 * 对应 Java: SystemUtils
 */
@Injectable()
export class SystemUtil {
  constructor(private readonly configService: ConfigService) {}

  /**
   * 获取系统信息
   */
  getSystemInfo(): {
    platform: string;
    arch: string;
    hostname: string;
    uptime: number;
    totalMemory: number;
    freeMemory: number;
    cpuCount: number;
    nodeVersion: string;
  } {
    return {
      platform: os.platform(),
      arch: os.arch(),
      hostname: os.hostname(),
      uptime: os.uptime(),
      totalMemory: os.totalmem(),
      freeMemory: os.freemem(),
      cpuCount: os.cpus().length,
      nodeVersion: process.version,
    };
  }

  /**
   * 获取内存使用情况
   */
  getMemoryUsage(): {
    rss: number;
    heapTotal: number;
    heapUsed: number;
    external: number;
    arrayBuffers: number;
  } {
    return process.memoryUsage();
  }

  /**
   * 获取 CPU 使用情况
   */
  getCpuUsage(): {
    model: string;
    speed: number;
    times: {
      user: number;
      nice: number;
      sys: number;
      idle: number;
      irq: number;
    };
  }[] {
    return os.cpus();
  }

  /**
   * 获取网络接口信息
   */
  getNetworkInterfaces(): NodeJS.Dict<os.NetworkInterfaceInfo[]> {
    return os.networkInterfaces();
  }

  /**
   * 获取环境变量
   */
  getEnv(key: string, defaultValue?: string): string | undefined {
    return process.env[key] || defaultValue;
  }

  /**
   * 获取所有环境变量
   */
  getAllEnv(): NodeJS.ProcessEnv {
    return process.env;
  }

  /**
   * 获取进程信息
   */
  getProcessInfo(): {
    pid: number;
    ppid: number;
    title: string;
    argv: string[];
    execPath: string;
    cwd: string;
    version: string;
    versions: NodeJS.ProcessVersions;
    platform: string;
    arch: string;
  } {
    return {
      pid: process.pid,
      ppid: process.ppid,
      title: process.title,
      argv: process.argv,
      execPath: process.execPath,
      cwd: process.cwd(),
      version: process.version,
      versions: process.versions,
      platform: process.platform,
      arch: process.arch,
    };
  }

  /**
   * 获取磁盘使用情况
   */
  async getDiskUsage(path: string = process.cwd()): Promise<{
    total: number;
    free: number;
    used: number;
    percentage: number;
  }> {
    try {
      const stats = await fs.promises.statfs(path);
      const total = stats.bavail * stats.bsize;
      const free = stats.bavail * stats.bsize;
      const used = total - free;
      const percentage = (used / total) * 100;

      return {
        total,
        free,
        used,
        percentage: Math.round(percentage * 100) / 100,
      };
    } catch (error) {
      throw new Error(`Failed to get disk usage: ${error.message}`);
    }
  }

  /**
   * 检查文件是否存在
   */
  async fileExists(filePath: string): Promise<boolean> {
    try {
      await fs.promises.access(filePath);
      return true;
    } catch {
      return false;
    }
  }

  /**
   * 创建目录
   */
  async createDirectory(
    dirPath: string,
    recursive: boolean = true,
  ): Promise<void> {
    await fs.promises.mkdir(dirPath, { recursive });
  }

  /**
   * 删除文件或目录
   */
  async removeFileOrDirectory(path: string): Promise<void> {
    const stats = await fs.promises.stat(path);
    if (stats.isDirectory()) {
      await fs.promises.rmdir(path, { recursive: true });
    } else {
      await fs.promises.unlink(path);
    }
  }

  /**
   * 复制文件
   */
  async copyFile(src: string, dest: string): Promise<void> {
    await fs.promises.copyFile(src, dest);
  }

  /**
   * 移动文件
   */
  async moveFile(src: string, dest: string): Promise<void> {
    await fs.promises.rename(src, dest);
  }

  /**
   * 读取文件内容
   */
  async readFile(
    filePath: string,
    encoding: BufferEncoding = 'utf8',
  ): Promise<string> {
    return fs.promises.readFile(filePath, encoding);
  }

  /**
   * 写入文件内容
   */
  async writeFile(
    filePath: string,
    content: string,
    encoding: BufferEncoding = 'utf8',
  ): Promise<void> {
    await fs.promises.writeFile(filePath, content, encoding);
  }

  /**
   * 获取文件信息
   */
  async getFileInfo(filePath: string): Promise<{
    size: number;
    isFile: boolean;
    isDirectory: boolean;
    mtime: Date;
    ctime: Date;
    atime: Date;
  }> {
    const stats = await fs.promises.stat(filePath);
    return {
      size: stats.size,
      isFile: stats.isFile(),
      isDirectory: stats.isDirectory(),
      mtime: stats.mtime,
      ctime: stats.ctime,
      atime: stats.atime,
    };
  }

  /**
   * 获取目录内容
   */
  async readDirectory(dirPath: string): Promise<string[]> {
    return fs.promises.readdir(dirPath);
  }

  /**
   * 获取文件扩展名
   */
  getFileExtension(filePath: string): string {
    return path.extname(filePath);
  }

  /**
   * 获取文件名（不含扩展名）
   */
  getFileNameWithoutExtension(filePath: string): string {
    return path.basename(filePath, path.extname(filePath));
  }

  /**
   * 获取目录名
   */
  getDirectoryName(filePath: string): string {
    return path.dirname(filePath);
  }

  /**
   * 连接路径
   */
  joinPath(...paths: string[]): string {
    return path.join(...paths);
  }

  /**
   * 解析路径
   */
  resolvePath(...paths: string[]): string {
    return path.resolve(...paths);
  }

  /**
   * 获取相对路径
   */
  getRelativePath(from: string, to: string): string {
    return path.relative(from, to);
  }

  /**
   * 检查路径是否为绝对路径
   */
  isAbsolutePath(filePath: string): boolean {
    return path.isAbsolute(filePath);
  }

  /**
   * 标准化路径
   */
  normalizePath(filePath: string): string {
    return path.normalize(filePath);
  }

  /**
   * 获取临时目录
   */
  getTempDirectory(): string {
    return os.tmpdir();
  }

  /**
   * 获取主目录
   */
  getHomeDirectory(): string {
    return os.homedir();
  }

  /**
   * 获取当前工作目录
   */
  getCurrentWorkingDirectory(): string {
    return process.cwd();
  }

  /**
   * 设置当前工作目录
   */
  setCurrentWorkingDirectory(directory: string): void {
    process.chdir(directory);
  }

  /**
   * 获取应用程序根目录
   */
  getAppRootDirectory(): string {
    return this.configService.get('app.root', process.cwd());
  }

  /**
   * 获取日志目录
   */
  getLogDirectory(): string {
    return this.configService.get(
      'app.logs',
      path.join(this.getAppRootDirectory(), 'logs'),
    );
  }

  /**
   * 获取上传目录
   */
  getUploadDirectory(): string {
    return this.configService.get(
      'app.uploads',
      path.join(this.getAppRootDirectory(), 'uploads'),
    );
  }

  /**
   * 获取配置目录
   */
  getConfigDirectory(): string {
    return this.configService.get(
      'app.config',
      path.join(this.getAppRootDirectory(), 'config'),
    );
  }

  /**
   * 获取缓存目录
   */
  getCacheDirectory(): string {
    return this.configService.get(
      'app.cache',
      path.join(this.getAppRootDirectory(), 'cache'),
    );
  }

  /**
   * 获取系统负载
   */
  getLoadAverage(): number[] {
    return os.loadavg();
  }

  /**
   * 获取系统运行时间
   */
  getUptime(): number {
    return os.uptime();
  }

  /**
   * 获取系统时间
   */
  getSystemTime(): Date {
    return new Date();
  }

  /**
   * 获取时区
   */
  getTimezone(): string {
    return Intl.DateTimeFormat().resolvedOptions().timeZone;
  }

  /**
   * 获取语言环境
   */
  getLocale(): string {
    return Intl.DateTimeFormat().resolvedOptions().locale;
  }

  /**
   * 检查是否为开发环境
   */
  isDevelopment(): boolean {
    return this.getEnv('NODE_ENV') === 'development';
  }

  /**
   * 检查是否为生产环境
   */
  isProduction(): boolean {
    return this.getEnv('NODE_ENV') === 'production';
  }

  /**
   * 检查是否为测试环境
   */
  isTest(): boolean {
    return this.getEnv('NODE_ENV') === 'test';
  }

  /**
   * 获取应用程序版本
   */
  getAppVersion(): string {
    return this.configService.get('app.version', '1.0.0');
  }

  /**
   * 获取应用程序名称
   */
  getAppName(): string {
    return this.configService.get('app.name', 'WWJCloud');
  }

  /**
   * 获取应用程序描述
   */
  getAppDescription(): string {
    return this.configService.get('app.description', 'WWJCloud Application');
  }

  /**
   * 获取应用程序作者
   */
  getAppAuthor(): string {
    return this.configService.get('app.author', 'WWJCloud Team');
  }

  /**
   * 获取应用程序许可证
   */
  getAppLicense(): string {
    return this.configService.get('app.license', 'MIT');
  }

  /**
   * 获取应用程序仓库
   */
  getAppRepository(): string {
    return this.configService.get('app.repository', '');
  }

  /**
   * 获取应用程序主页
   */
  getAppHomepage(): string {
    return this.configService.get('app.homepage', '');
  }

  /**
   * 获取应用程序关键词
   */
  getAppKeywords(): string[] {
    const keywords = this.configService.get('app.keywords', '');
    return keywords ? keywords.split(',').map((k) => k.trim()) : [];
  }
}
